package cn.hg.jbsa.config;

import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

import cn.hg.jboot.core.constant.BaseConstants;
import cn.hg.jboot.core.exception.BaseServiceException;
import io.jboot.support.shiro.JbootShiroInvokeListener;
import io.jboot.support.shiro.processer.AuthorizeResult;

/**
 * @author 胡高
 * @date 2022/04/18
 */
public class JbsaShiroInvokeListener implements JbootShiroInvokeListener {

    public void doProcessUnauthenticated(Controller controller) {
        // 处理认证失败
        throw new BaseServiceException(BaseConstants.RETURN_CODE_VALUE_FAILED, "您未登录或登录已超时！");
    }

    public void doProcessuUnauthorization(Controller controller) {
        // 处理授权失败
        throw new BaseServiceException(BaseConstants.RETURN_CODE_VALUE_FAILED, "您没有此操作的权限！");
    }

    /* (non-Javadoc)
     * @see io.jboot.support.shiro.JbootShiroInvokeListener#onInvokeAfter(com.jfinal.aop.Invocation, io.jboot.support.shiro.processer.AuthorizeResult)
     */
    @Override
    public void onInvokeAfter(Invocation inv, AuthorizeResult result) {
        //说明该用户授权成功，
        //可以允许访问
        if (result.isOk()) {
            inv.invoke();
            return;
        }

        //shiro授权不成功，返回授权错误码
        int errorCode = result.getErrorCode();
        switch (errorCode) {
            case AuthorizeResult.ERROR_CODE_UNAUTHENTICATED:
                this.doProcessUnauthenticated(inv.getController());
                break;
            case AuthorizeResult.ERROR_CODE_UNAUTHORIZATION:
                this.doProcessuUnauthorization(inv.getController());
                break;
            default:
                inv.getController().renderError(404);
        }
    }

    /* (non-Javadoc)
     * @see io.jboot.support.shiro.JbootShiroInvokeListener#onInvokeBefore(com.jfinal.aop.Invocation)
     */
    @Override
    public AuthorizeResult onInvokeBefore(Invocation inv) {
        return AuthorizeResult.ok();
    }

}
